package com.wxy.demo.controller;

import com.wxy.demo.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
@Slf4j
public class UserController {

    @PostMapping("/save")
    @ApiOperation("添加用户")
    public User save(@RequestBody @Valid User user) {
        return user;
    }

    @PostMapping("/saveBatch")
    @ApiOperation("批量添加用户")
    public List<User> saveBatch(@RequestBody @Valid List<User> list) {
        AtomicInteger i = new AtomicInteger();
        list.forEach(user -> user.setId(i.incrementAndGet()));
        return list;
    }

    @PostMapping("/update")
    @ApiOperation("修改用户")
    public User update(@RequestBody(required = false) @Valid User user) {
        return user;
    }

    @PostMapping("/setPwd")
    @ApiOperation("设置密码")
    public String setPwd(@RequestBody String pwd) {
        return pwd;
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除用户")
    public Integer delete(@PathVariable Integer id) {
        return id;
    }

    @GetMapping("/getOne")
    @ApiOperation("根据id查询用户")
    public User getOne(@RequestParam Integer id) {
        return new User().setId(id).setUsername("张三").setAge(20).setSex("男");
    }

    @PostMapping("/saveUserMap")
    @ApiOperation("保存用户")
    public Map<String, Object> saveUserMap(@RequestBody Map<String, Object> map) {
        return map;
    }

    @GetMapping("/findAll")
    @ApiOperation("查询用户列表")
    public ArrayList<User> findAll(@RequestParam(required = false) String username) {
        ArrayList<User> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new User().setId(i).setUsername(Optional.ofNullable(username).orElse("张三") + i)
                    .setAge(i + 10).setSex("男"));
        }
        return list;
    }

    @GetMapping("/findIds")
    @ApiOperation("查询用户ids")
    public ArrayList<Integer> findIds() {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        return list;
    }

    @DeleteMapping("/deleteAll")
    @ApiOperation("删除所有用户")
    public void deleteAll() {
        log.info("删除所有用户...");
    }

}
